package org.mybatis.generator.plugins.js.elements;

import java.util.List;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.xml.TextElement;

/**
 * 
 * @author super_dev_001
 * 
 */
public class ExtJsMethodGenerator {

	private IntrospectedTable introspectedTable;

	private String targetModel;

	private String tableName;

	private String tableLab;

	private String code;

	public ExtJsMethodGenerator(IntrospectedTable introspectedTable,
			String targetModel) {
		this.introspectedTable = introspectedTable;
		this.targetModel = targetModel;
		tableName = introspectedTable.getTableConfiguration().getTableName();
		tableName=toLowerCase(tableName);
		tableLab = introspectedTable.getRemarks();
		while (tableName.lastIndexOf("_") != -1) {
			int index = tableName.lastIndexOf("_");
			tableName = tableName.replaceFirst(
					"_" + tableName.substring(index + 1, index + 2), tableName
							.substring(index + 1, index + 2).toUpperCase());
		}
		code = targetModel + "_" + tableName;
	}

	/**
	 * 获取控制器方法
	 * 
	 * @return
	 */
	public TextElement getControllerMethod() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ext.define(\"yy." + targetModel + ".controller."
				+ tableName + "Controller\", {");
		sb.append("extend : \"Ext.app.Controller\",");
		sb.append("mixins : {gridUtils : \"yy.utils.dataGridUtils\",},");
		sb.append("init : function() {");
		sb.append("var self = this;");
		sb.append("this.getTreeObj = function(buttion) {return buttion.ownerCt.ownerCt;};");
		sb.append("this.control({");

		sb.append("'" + tableName + "View ': {afterrender : function(gp) {");
		sb.append("buttonFilter(\"" + code + "\");");
		sb.append("}},");

		sb.append("'" + tableName + "View button[action=" + code
				+ "_edit]' : {click : function(b) {");
		sb.append("var dataGrid = this.getTreeObj(b);");
		sb.append("var url = '" + targetModel + "/" + tableName
				+ "/modify';");
		sb.append("this.doEditWithParams('yy." + targetModel + ".view." + tableName
				+ "Win', dataGrid, url,{gridName:'"+tableName+"Grid'});");
		sb.append("}},");

		sb.append("'" + tableName + "View button[action=" + code
				+ "_add]' : {");
		sb.append("click : function(b) {");
		sb.append("var url = '" + targetModel + "/" + tableName + "/add';");
		sb.append("self.doAddWithParams('yy." + targetModel + ".view." + tableName
				+ "Win', url,{gridName:'"+tableName+"Grid'});");
		sb.append("}},");

		sb.append("'" + tableName + "View button[action=" + code
				+ "_delete]' : {");
		sb.append("click : function(btn) {");
		sb.append("var dataGrid = this.getTreeObj(btn);");
		sb.append("self.doDelete(dataGrid, \"" + targetModel + "/" + tableName
				+ "/deleteByBatch\", \"id\");");
		sb.append("}},");
		
		/**
		sb.append("'" + tableName + "View button[action=" + code
				+ "_logicDelete]' : {");
		sb.append("click : function(btn) {");
		sb.append("var grid = this.getTreeObj(btn);");
		sb.append("self.doDelete(grid, \"" + targetModel + "/" + tableName
				+ "/logicDelete\", \"id\");");
		sb.append("}},");
		
		sb.append("'" + tableName + "View button[action=" + code
				+ "_recover]' : {");
		sb.append("click : function(btn) {");
		sb.append("var grid = this.getTreeObj(btn);");
		sb.append("self.doRecovery(grid, \"" + targetModel + "/" + tableName
				+ "/recover\", \"id\");");
		sb.append("}},");
		*/
		
		
		sb.append("'" + tableName + "View button[action=" + code
				+ "_show]' : {click : function(b) {");
		sb.append("var dataGrid = this.getTreeObj(b);");
		sb.append("var url = '" + targetModel + "/" + tableName
				+ "/modify';");
		sb.append("this.doEdit('yy." + targetModel + ".view." + tableName
				+ "ShowWin', dataGrid, url);");
		sb.append("}},");

		/*sb.append("'" + tableName + "Win button[action=save]' : {");
		sb.append("click : function(b) {");
		sb.append("var form = Ext.getCmp('" + tableName + "Form').getForm();");
		sb.append("var dataGrid = Ext.getCmp('" + tableName + "Grid');");
		sb.append("var win = Ext.getCmp('" + tableName + "Win');");
		sb.append("this.doSave(dataGrid, form, win);");
		sb.append("}},");*/

		sb.append("'" + tableName + "View button[action=search]' : {");
		sb.append("click : function(o) {");
		sb.append("var dataGrid = Ext.getCmp('" + tableName + "Grid');");
		sb.append("var form = Ext.getCmp('" + tableName + "Search').getForm();");
		sb.append("this.doSearch(dataGrid, form);");
		sb.append("}},");

		sb.append("'" + tableName + "View button[action=clear]' : {");
		sb.append("click : function(o) {");
		sb.append("var dataGrid = Ext.getCmp('" + tableName + "Grid');");
		sb.append("var form = Ext.getCmp('" + tableName + "Search').getForm();");
		sb.append("this.doClearSearch(dataGrid, form);");
		sb.append("}}");

		sb.append("});},");

		sb.append("views : [],");
		sb.append("stores : [ \"yy." + targetModel + ".store." + tableName
				+ "Store\" ],");
		sb.append("models : [ \"yy." + targetModel + ".model." + tableName
				+ "Model\" ]");

		sb.append("});");
		return new TextElement(sb.toString());
	}

	/**
	 * 获取模型类型
	 * 
	 * @return
	 */
	public TextElement getModelMethod() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ext.define(\"yy." + targetModel + ".model." + tableName
				+ "Model\", {");
		sb.append("extend : \"Ext.data.Model\",");
		sb.append("fields : [");
		List<IntrospectedColumn> columns = introspectedTable.getAllColumns();
		for (IntrospectedColumn column : columns) {
			FullyQualifiedJavaType fqjt = column.getFullyQualifiedJavaType();
			sb.append("{name : \"");
			sb.append(column.getJavaProperty());
			sb.append("\",");
			if (fqjt.getShortName().equals("Integer")) {
				sb.append("type : \"int\",convert: null,");
			} else if (fqjt.getShortName().equals("String")) {
				sb.append("type : \"string\",");
			} else if(fqjt.getShortName().equals("Date")){
				sb.append("convert : function(v, record) {if(!v){return null;}return Ext.util.Format.date(new Date(v), 'Y-m-d H:i:s');},");
			} else if(fqjt.getShortName().equals("Boolean")){
				sb.append("type : \"boolean\",convert: null,");
			}
			sb.append("srotable : true},");
		}
		sb.append("]});");
		return new TextElement(sb.toString());
	}

	/**
	 * 获取数据请求代码
	 * 
	 * @return
	 */
	public TextElement getStoreMethod() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ext.define(\"yy." + targetModel + ".store." + tableName
				+ "Store\", {");
		sb.append("extend : 'Ext.data.Store',");
		sb.append("model : 'yy." + targetModel + ".model." + tableName
				+ "Model',");
		sb.append("pageSize : 10,");
		sb.append("proxy : {");
		sb.append("type : \"ajax\",");
		sb.append("actionMethods : {read : 'POST'},");
		sb.append("url : \"" + targetModel + "/" + tableName + "/query\",");
		sb.append("reader : {");
		sb.append("type : \"json\",");
		sb.append("root : \"rows\",");
		sb.append("totalProperty : 'totalCount'");
		sb.append("},");
		sb.append("writer : {type : \"json\"}},");
		sb.append("autoLoad : false,");
		sb.append("remoteSort : true");
		sb.append("});");
		return new TextElement(sb.toString());
	}

	/**
	 * 获取所有数据请求代码
	 * 
	 * @return
	 */
	public TextElement getAllStoreMethod() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ext.define(\"yy." + targetModel + ".store." + tableName
				+ "AllStore\", {");
		sb.append("extend : 'Ext.data.Store',");
		sb.append("model : 'yy." + targetModel + ".model." + tableName
				+ "Model',");
		sb.append("pageSize : 10,");
		sb.append("proxy : {");
		sb.append("type : \"ajax\",");
		sb.append("actionMethods : {read : 'POST'},");
		sb.append("url : \"" + targetModel + "/" + tableName
				+ "/queryByAll\",");
		sb.append("reader : {");
		sb.append("type : \"json\",");
		sb.append("root : \"rows\",");
		sb.append("totalProperty : 'totalCount'");
		sb.append("},");
		sb.append("writer : {type : \"json\"}},");
		sb.append("autoLoad : false,");
		sb.append("remoteSort : true");
		sb.append("});");
		return new TextElement(sb.toString());
	}

	public TextElement getViewMethod() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ext.define(\"yy." + targetModel + ".view." + tableName
				+ "View\", {");
		sb.append("extend : 'Ext.panel.Panel',");
		sb.append("alias : 'widget." + tableName + "View',");
		sb.append("title :\"<center height=40>" + tableLab + "管理</center>\",");
		sb.append("closable : true,");
		sb.append("defaults : {bodyStyle : 'padding:1px'},");
		sb.append("layout : 'fit',");
		sb.append("initComponent : function() {");
		sb.append("var " + tableName + "Grid = Ext.widget('gridpanel', {");
		sb.append("region : 'center',");
		sb.append("id : '" + tableName + "Grid',");
		sb.append("columnLines : true,");
		sb.append("forceFit : true,");
		sb.append("selType : 'checkboxmodel',");
		sb.append("multiSelect : true,");
		sb.append("columns : [");
		sb.append("{xtype : 'rownumberer'}");

		List<IntrospectedColumn> columns = introspectedTable.getAllColumns();
		for (IntrospectedColumn column : columns) {
			if (!column.getJavaProperty().equals("id")) {
				sb.append(",{text : \"");
				sb.append(column.getRemarks());
				sb.append("\",dataIndex : \"");
				sb.append(column.getJavaProperty());
				sb.append("\",width : 200");

				FullyQualifiedJavaType fqjt = column.getFullyQualifiedJavaType();
				if(fqjt.getShortName().equals("Integer")){
					sb.append(",renderer : function(_value,mata,_record) {");
					sb.append("if(!_value){return null;}return yy.utils.dicRender(yy.global.type.DictStore."+column.getJavaProperty()+",_value);");
					sb.append("}");
				}else if(fqjt.getShortName().equals("Boolean")){
					sb.append(",renderer : function(_value,mata,_record) {");
					sb.append("if(_value==null || _value==undefined){return null;}return yy.utils.dicRender(yy.global.type.DictStore.bool,_value);");
					sb.append("}");
				}

				sb.append("}");
			}
		}
		sb.append("],");
		sb.append("tbar : [ ");
		sb.append("{xtype : 'button',text : '添加',iconCls : 'table_add',action : '"
				+ code + "_add',id:'" + code + "_add',hidden : true},");
		sb.append("{xtype : 'button',text : '修改',iconCls : 'table_edit',action : '"
				+ code + "_edit',id:'" + code + "_edit',hidden : true},");
		sb.append("{xtype : 'button',text : '删除',iconCls : 'table_remove',action : '"
				+ code + "_delete',id:'" + code + "_delete',hidden : true},");
		sb.append("{xtype : 'button',text : '查看',iconCls : 'table_show',action : '"
				+ code + "_show',id:'" + code + "_show',hidden : true},");
//		sb.append("{xtype : 'button',text : '删除',iconCls : 'table_remove',action : '"
//				+ code + "_logicDelete',id:'" + code + "_logicDelete',hidden : true},");
//		sb.append("{xtype : 'button',text : '恢复',iconCls : 'table_refresh',action : '"
//				+ code + "_recover',id:'" + code + "_recover',hidden : true},");
		sb.append("],");
		sb.append("bbar: Ext.create('Ext.PagingToolbar', {");
		sb.append("plugins: [new Ext.ux.ComboPageSize({})],");
		sb.append("store : 'yy." + targetModel + ".store." + tableName
				+ "Store',");
		sb.append(" displayInfo: true,");
		sb.append(" displayMsg: '显示 {0} - {1} 条，共计 {2} 条',");
		sb.append("emptyMsg: \"没有数据\"");
		sb.append("}),");

		sb.append("listeners : {");
		sb.append("itemdblclick : function(_this, record, item, index) {");
//		sb.append("var url = '" + targetModel + "/" + tableName
//				+ "/modify';");
//		sb.append("var win = Ext.create(\"yy." + targetModel + ".view."
//				+ tableName + "Win\");");
//		sb.append("win.down('form').getForm().loadRecord(record);");
//		sb.append("win.url = url;");
//		sb.append("win.show();");
		sb.append("}");
		sb.append("},");

		sb.append("store : 'yy." + targetModel + ".store." + tableName
				+ "Store'");
		sb.append("});");
		// 查询
		sb.append("var " + tableName + "Search = Ext.widget('form', {");
		sb.append("region : 'north',");
		sb.append("border : false,");
		sb.append("bodyPadding : 5,");
		sb.append("title : '条件过滤',");
		sb.append("id : '" + tableName + "Search',");
		sb.append("collapsible : true,");
		sb.append("collapsed : true,");
		sb.append("defaultType : 'textfield',");
		sb.append("items : [ ");
		// sb.append("{fieldLabel : '名称',name : 'name'}");
		// 查询开始
		sb.append("{xtype : \"container\",");
		sb.append("defaultType : \"textfield\",");
		sb.append("style : \"padding-left:0px;\",");
		sb.append("columnWidth : 0.2,");
		sb.append("defaults : {anchor : \"96%,96%\"},");
		sb.append("layout : \"form\",");
		sb.append("items : [ {");
		sb.append("xtype : \"container\",");
		sb.append("layout : \"column\",");
		sb.append("defaults: {labelAlign : 'right',columnWidth: 0.2,margin: '5 0 0 0',labelWidth: 60,xtype: 'textfield',},");
		sb.append("style : \"padding-left:0px;\",");
		sb.append("items : [");

		for (IntrospectedColumn column : columns) {
			if (!column.getJavaProperty().equals("id")
					&& !column.getJavaProperty().equals("content")
					&& !column.getJavaProperty().equals("metaKeywords")
					&& !column.getJavaProperty().equals("metaDescription")
					&& !column.getJavaProperty().equals("metaTitle")
					&& !column.getJavaProperty().equals("createTime")
					&& !column.getJavaProperty().equals("modifyTime")
					&& !column.getJavaProperty().equals("remark")) {
//				sb.append("{xtype : \"container\",");
//				sb.append("defaultType : \"textfield\",");
//				sb.append("style : \"padding-left:0px;\",");
//				sb.append("columnWidth : 0.2,");
//				sb.append("layout : \"form\",");
//				sb.append("items : [ {");
				sb.append("{fieldLabel : '" + column.getRemarks() + "',");
				sb.append("name : '" + column.getJavaProperty() + "',");
				FullyQualifiedJavaType fqjt = column.getFullyQualifiedJavaType();
				if(fqjt.getShortName().equals("Integer")){
					sb.append("store:yy.global.type.DictStore."+column.getJavaProperty()+",editable:false,xtype:'combo'");
				}else if(fqjt.getShortName().equals("Boolean")){
					sb.append("store:yy.global.type.DictStore.bool,editable:false,xtype:'combo'");
				}
				sb.append("}, ");
//				sb.append("]},");
			}

		}

		sb.append("]");
		sb.append("} ]");
		sb.append("}");
		// 查询结束
		sb.append("],");
		sb.append("buttons : [");
		sb.append("{text : '查询',action : 'search'}, ");
		sb.append("{text : '清空',action : 'clear'}] ");
		sb.append("});");
		sb.append("Ext.apply(this, {");
		sb.append("layout : 'border',");
		sb.append("items : [ " + tableName + "Grid, " + tableName + "Search ]");
		sb.append("});");
		sb.append("this.callParent(arguments);");
		sb.append("}});");
		return new TextElement(sb.toString());
	}

	public TextElement getWinMethod() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ext.define('yy." + targetModel + ".view." + tableName
				+ "Win', {");
		sb.append("extend : 'Ext.window.Window',");
		sb.append("plain : true,");
		sb.append("minimizable : true,");
		sb.append("closeAction : 'destroy',");
		sb.append("modal : true,");
		sb.append("alias : 'widget." + tableName + "Win',");
		sb.append("mixins: {gridUtils: \"yy.utils.dataGridUtils\",},");
		sb.append("initComponent : function() {");
		sb.append("var self = this;");
		sb.append("var basePanel = {");
		sb.append("xtype : 'fieldset',title : '基本信息',");
		sb.append("defaults : {anchor : '100%'},");
		sb.append("collapsed : false,collapsible : true,");
		sb.append("items : [ {");
		sb.append("xtype : 'container',layout : 'hbox',");
		sb.append("items : [ {");
		sb.append("xtype : 'container',flex : 1,");
		sb.append("layout : 'column',");
		sb.append("defaults: {labelAlign : 'right',columnWidth: 0.5,margin: '5 0 0 0',labelWidth: 60,xtype: 'textfield',},");
		sb.append("items : [ {name : 'id',xtype:'hidden'}");

		List<IntrospectedColumn> columns = introspectedTable.getBaseColumns();
		for (IntrospectedColumn column : columns) {
			if (!column.getJavaProperty().equals("createTime")
					&& !column.getJavaProperty().equals("id")) {
				sb.append(",{fieldLabel : '" + column.getRemarks() + "',");
				sb.append("name : '" + column.getJavaProperty() + "',");
				sb.append("id : '" + column.getJavaProperty() + "',");
				FullyQualifiedJavaType fqjt = column.getFullyQualifiedJavaType();
				if(fqjt.getShortName().equals("Integer")){
					sb.append("store : yy.global.type.DictStore."+column.getJavaProperty()+",");
					sb.append("xtype : 'combo',");
					sb.append("editable : false,");
				}else if(fqjt.getShortName().equals("Boolean")){
					sb.append("store : yy.global.type.DictStore.bool,");
					sb.append("xtype : 'combo',");
					sb.append("editable : false,");
				}

				sb.append("allowBlank : false,");
				sb.append("blankText : '" + column.getRemarks() + "不能为空!',");
				sb.append("afterLabelTextTpl : required}");
			}
		}
		sb.append("]");
		sb.append("} ]} ]};");
		sb.append("var form = Ext.widget('form', {");
		sb.append("id : '" + tableName + "Form',");
		sb.append("fieldDefaults : {labelWidth : 80},");
		sb.append("width : 600,bodyPadding : 10,");
		sb.append("items : [ basePanel ],");
		sb.append("buttons : [ {text : '保存',action : 'save',");
		sb.append("handler:function(){var form = Ext.getCmp('"+tableName+"Form').getForm();var dataGrid = Ext.getCmp(self.gridName);")
				.append("var win = Ext.getCmp('"+tableName+"Win');self.doSave(dataGrid, form, win);}},");
		sb.append(" {text : '取消',action : 'cancel',handler:function(){self.close();}} ]");
		sb.append("});");
		sb.append("Ext.apply(this, {");
		sb.append("id : '" + tableName + "Win',");
		sb.append("title : '" + tableLab + "增改',");
		sb.append("closable : true,");
		sb.append("layout : 'fit',");
		sb.append("modal : true,");
		sb.append("constrain : true,");
		sb.append("items : form");
		sb.append("});");
		sb.append("this.callParent(arguments);");
		sb.append("}");
		sb.append("});");
		return new TextElement(sb.toString());
	}

	public TextElement getShowWinMethod() {
		StringBuilder sb = new StringBuilder();
		sb.append("Ext.define('yy." + targetModel + ".view." + tableName
				+ "ShowWin', {");
		sb.append("extend : 'Ext.window.Window',");
		sb.append("plain : true,");
		sb.append("minimizable : true,");
		sb.append("closeAction : 'destroy',");
		sb.append("modal : true,");
		sb.append("alias : 'widget." + tableName + "ShowWin',");
		sb.append("initComponent : function() {");
		sb.append("var basePanel = {");
		sb.append("xtype : 'fieldset',title : '基本信息',");
		sb.append("defaults : {anchor : '100%'},");
		sb.append("collapsed : false,collapsible : true,");
		sb.append("items : [ {");
		sb.append("xtype : 'container',layout : 'hbox',");
		sb.append("items : [ {");
		sb.append("xtype : 'container',flex : 1,");
		sb.append("layout: 'column',defaults: {labelAlign : 'right',columnWidth: 0.5,margin: '5 0 0 0',labelWidth: 60,xtype: 'displayfield',},");
//		sb.append("layout : 'anchor',defaultType : 'textfield',style : 'padding-left:10px;padding-right:10px;',");
		sb.append("items : [ ");

		List<IntrospectedColumn> columns = introspectedTable.getBaseColumns();
		for (IntrospectedColumn column : columns) {
			if (!column.getJavaProperty().equals("id")) {
				sb.append("{fieldLabel : '" + column.getRemarks() + "',");
				sb.append("name : '" + column.getJavaProperty() + "',");

				FullyQualifiedJavaType fqjt = column.getFullyQualifiedJavaType();
				if(fqjt.getShortName().equals("Integer")){
					sb.append("renderer : function(_value,mata,_record) {if(!_value){ return null;}" +
							"return yy.utils.dicRender(yy.global.type.DictStore."+column.getJavaProperty()+",_value);},");
				}else if(fqjt.getShortName().equals("Boolean")){
					sb.append("renderer : function(_value,mata,_record) {if(_value==null || _value==undefined){ return null;}" +
							"return yy.utils.dicRender(yy.global.type.DictStore.bool,_value);},");
				}
				sb.append("},");
			}
		}
		sb.append("]");
		sb.append("} ]} ]};");
		sb.append("var form = Ext.widget('form', {");
		sb.append("id : '" + tableName + "ShowForm',");
		sb.append("fieldDefaults : {labelWidth : 80},");
		sb.append("width : 600,bodyPadding : 10,");
		sb.append("items : [ basePanel ],");
		sb.append("buttons : []");
		sb.append("});");
		sb.append("Ext.apply(this, {");
		sb.append("id : '" + tableName + "ShowWin',");
		sb.append("title : '" + tableLab + "信息',");
		sb.append("closable : true,");
		sb.append("layout : 'fit',");
		sb.append("modal : true,");
		sb.append("constrain : true,");
		sb.append("items : form");
		sb.append("});");
		sb.append("this.callParent(arguments);");
		sb.append("}");
		sb.append("});");
		return new TextElement(sb.toString());
	}

	/**
	 * BaseUsers to baseUsers
	 * 
	 * @param tableName
	 * @return
	 */
	protected String toLowerCase(String tableName) {
		StringBuilder sb = new StringBuilder(tableName);
		sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
		return sb.toString();
	}

	/**
	 * BaseUsers to baseUsers
	 * 
	 * @param tableName
	 * @return
	 */
	protected String toUpperCase(String tableName) {
		StringBuilder sb = new StringBuilder(tableName);
		sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
		return sb.toString();
	}
}
